import React from "react";
import { connect } from "react-redux";
import { Form, Input, Button, List, Divider, Modal } from "antd";

class App extends React.Component {
  state = {
    loading: false,

    visible: false,
    editTodoInfo: null,
    confirmLoading: false
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.addTodo(values);
      }
    });
  };

  render() {
    const {
      todos,
      delTodo,
      updateTodo,
      form: { getFieldDecorator }
    } = this.props;

    const { loading, visible, editTodoInfo, confirmLoading } = this.state;

    return (
      <div className="todo-app">
        <h1>TodoApp</h1>

        <Form layout="inline" onSubmit={this.handleSubmit}>
          <Form.Item>
            {getFieldDecorator("name", {
              rules: [{ required: true, message: "请输入Todo" }]
            })(<Input placeholder="Todo" />)}
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              Add
            </Button>
          </Form.Item>
        </Form>

        <Divider />

        <List
          bordered
          loading={loading}
          dataSource={todos}
          renderItem={item => (
            <List.Item>
              <span>{item.name}</span>

              <ul className="ant-list-item-action">
                <li>
                  <Button
                    type="primary"
                    icon="edit"
                    onClick={() => {
                      this.setState({
                        visible: true,
                        editTodoInfo: item
                      });
                    }}
                  ></Button>
                </li>
                <li>
                  <Button
                    type="danger"
                    icon="delete"
                    onClick={() => {
                      delTodo(item);
                    }}
                  ></Button>
                </li>
              </ul>
            </List.Item>
          )}
        />

        <EditModel
          title="编辑"
          visible={visible}
          confirmLoading={confirmLoading}
          width={320}
          editTodoInfo={editTodoInfo}
          ref={e => (this.editModel = e)}
          onCancel={() => {
            this.setState({
              visible: false,
              editTodoInfo: null
            });
          }}
          onOk={() => {
            this.editModel.validateFields((err, values) => {
              if (!err) {
                this.setState({
                  confirmLoading: true
                });
                updateTodo(values, () => {
                  this.setState({
                    confirmLoading: false,
                    visible: false
                  });
                });
              }
            });
          }}
        ></EditModel>
      </div>
    );
  }

  componentDidMount() {
    this.setState({ loading: true });
    this.props.initTodo(() => {
      this.setState({ loading: false });
    });
  }
}

class EditModel extends React.Component {
  render() {
    const {
      form: { getFieldDecorator },
      editTodoInfo,
      ...rest
    } = this.props;

    return (
      <Modal {...rest}>
        <Form>
          <Form.Item>
            {getFieldDecorator("name", {
              rules: [{ required: true, message: "请输入Todo" }],
              initialValue: editTodoInfo && editTodoInfo.name
            })(<Input placeholder="Todo" />)}
          </Form.Item>
          <Form.Item style={{ display: "none" }}>
            {getFieldDecorator("id", {
              rules: [{ required: true, message: "请输入Todo" }],
              initialValue: editTodoInfo && editTodoInfo.id
            })(<Input placeholder="Todo" />)}
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

EditModel = Form.create()(EditModel);

export default connect(
  state => ({
    todos: state.todos
  }),
  {
    /**
     * 初始化todo
     */
    initTodo(cb) {
      return dispatch => {
        fetch("http://localhost:9090/todos")
          .then(response => response.json())
          .then(data => {
            dispatch({
              type: "INIT_TODO",
              todos: data
            });

            cb && cb();
          });
      };
    },

    /**
     * 添加todo
     */
    addTodo(values) {
      return dispatch => {
        fetch("http://localhost:9090/todos", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            name: values.name
          })
        })
          .then(response => response.json())
          .then(data => {
            dispatch({
              type: "ADD_TODO",
              todo: data
            });
          });
      };
    },

    /**
     * 删除todo
     */
    delTodo(todo) {
      return dispatch => {
        let url = `http://localhost:9090/todos/${todo.id}`;
        fetch(url, {
          method: "DELETE"
        })
          .then(response => response.json())
          .then(data => {
            dispatch({
              type: "DEL_TODO",
              todo
            });
          });
      };
    },

    /**
     * 修改todo
     */
    updateTodo(values, cb) {
      return dispatch => {
        let url = `http://localhost:9090/todos/${values.id}`;
        fetch(url, {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            name: values.name
          })
        })
          .then(response => response.json())
          .then(data => {
            dispatch({
              type: "UPDATE_TODO",
              todo: data
            });

            cb && cb();
          });
      };
    }
  }
)(Form.create()(App));
